package com.aijk.web.admin.utils;

import java.io.*;

/**
 * IO处理工具 
 * @author 胡永伟
 * @version 1.0.0
 * @date 2015年10月15日 下午11:44:46
 * @since 1.0.0
 */
public final class IOUtil {
	
	private IOUtil() {}
	
	/**
	 * 将InputStream中的数据转存到OutputStream中
	 * @param in 输入流
	 * @param outs 输出流可变参数
	 */
	public static void transfer(InputStream in, 
			OutputStream... outs) throws IOException {
		byte[] buf = new byte[1024];
		int len = 0;
		while ((len = in.read(buf)) != -1) {
			for (OutputStream out : outs) {
				out.write(buf, 0, len);
			}
		}
	}
	
	/**
	 * 将数据流转换成字符串
	 * @param istream 输入流
	 * @return 字符串
	 */
	public static String stringify(InputStream istream) {
		return stringify(istream, "UTF-8", true);
	}
	
	/**
	 * 将数据流转换成字符串
	 * @param istream 输入流
	 * @param charset 字符集
	 * @param close 是否关闭流
	 * @return 字符串
	 */
	public static String stringify(
			InputStream istream, String charset, boolean close) {
		BufferedReader reader = null;
		StringBuilder sb = new StringBuilder();
		try {
			reader = new BufferedReader(new InputStreamReader(istream, charset));
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace(System.err);
		} finally {
			if (close) {
				close(reader);
			}
		}
		return sb.toString();
	}
	
	/**
	 * 关闭指定可关闭对象(数组)
	 * @param closeables 可关闭的对象(数组)
	 */
	public static void close(Closeable ... closeables) {
		for (Closeable closeable : closeables) {
			if (closeable != null) {
				try {
					closeable.close();
				} catch (IOException e) {
					e.printStackTrace(System.err);
				}
				closeable = null;
			}
		}
	}
	
}
